<template>
    <el-container>
        <el-header class="header">
            <div class="left-panel">
                <el-form class="search-form" ref="formRefSearch" :inline="true" :model="formSearch">
                    <el-form-item prop="LoginName">
                        <el-input v-model="formSearch.LoginName" placeholder="登录名" clearable class="!w-[180px]" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" icon="Search" @click="onSearch">搜索</el-button>
                        <el-button type="info" icon="RefreshLeft" @click="resetForm(formRefSearch)">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="right-panel">
                <el-button type="primary" size="default" icon="Plus" @click="addUser">新增用户</el-button>
                <el-button type="danger" size="default" icon="Delete" @click="deleteUser">批量删除</el-button>
            </div>
        </el-header>
        <el-main class="main">
            <el-table border :data="userArr" height="calc(100vh - 280px)" :stripe="true" :highlight-current-row="true"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
                <el-table-column label="登录名" prop="loginName" align="center">
                </el-table-column>
                <el-table-column label="用户名" prop="realName" align="center">
                </el-table-column>
                <el-table-column label="用户角色" prop="roleNames" align="center">
                </el-table-column>
                <el-table-column label="用户状态" prop="status" align="center">
                    <template #default="scope">
                        {{ scope.row.status == 0 ? '启用' : '禁用' }}
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" prop="createTime" align="center">
                </el-table-column>
                <el-table-column label="用户操作" align="center">
                    <template #="{ row, $index }">
                        <el-button type="warning" size="default" icon="Edit" v-show="row.isSeed !== 0"
                            @click="updateUser(row)">修改</el-button>
                        <el-popconfirm :title="`您确定要删除${row.loginName}?`" width="250px" icon="Delete"
                            @confirm='removeUser(row.id)'>
                            <template #reference>
                                <el-button type="danger" size="default" icon="Delete"
                                    v-show="row.isSeed !== 0">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" @size-change="sizeChange" @current-change="getUser" :pager-count="9"
                v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[10, 20, 50, 100]"
                :background="true" layout="total,sizes,prev, pager, next, jumper" :total="total" />
        </el-main>
    </el-container>
    <el-dialog v-model="dialogFormVisible" :title="userParams.id ? '修改用户' : '新增用户'">
        <el-form :model="userParams" :rules="rules" ref="formRef">
            <el-form-item label="登录名" label-width="100px" prop="loginName">
                <el-input placeholder="请您输入登录名" v-model="userParams.loginName"></el-input>
            </el-form-item>
            <el-form-item label="用户名" label-width="100px" prop="realName">
                <el-input placeholder="请您输入用户名" v-model="userParams.realName"></el-input>
            </el-form-item>
            <el-form-item label="用户角色" label-width="100px" prop="roleIds">
                <el-select v-model="userParams.roleIds" multiple clearable placeholder="请选择用户角色">
                    <el-option v-for="item in optionRoles" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" size="default" @click="cancel">取消</el-button>
            <el-button type="primary" size="default" @click="confirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus'
import { getUserListApi, reqAddOrUpdateUserApi, reqDeleteUserApi } from "@/api/modules/user";
import { getRoleListApi } from "@/api/modules/role"

let pageNo = ref<number>(1);
let limit = ref<number>(10);
let total = ref<number>(0);
let userArr = ref([]);
const selectable = (row) => ![1].includes(row.id)
let dialogFormVisible = ref<boolean>(false)
let userParams = reactive({
    id: 0,
    loginName: '',
    realName: '',
    loginPWD: '',
    roleIds: []
})
let formSearch = reactive({
    LoginName: ''
})
let pageCon = reactive({
    PageNum: pageNo.value,
    PageSize: limit.value
})
const loading = ref(false);
let formRef = ref();
let formRefSearch = ref();
let deleteIds = reactive([])
let optionRoles = ref([])

onMounted(() => {
    getUser();
    getRole();
});
const getUser = async (pager = 1) => {
    pageNo.value = pager;    
    let result = await getUserListApi({...formSearch, ...pageCon});
    if (result?.status == 200) {
        total.value = result.response.dataCount;
        userArr.value = result.response.data;
    }
}
const getRole = async () => {
    let result = await getRoleListApi();
    optionRoles.value = result.response;
}
const sizeChange = () => {
    getUser();
}
const addUser = () => {
    dialogFormVisible.value = true;
    userParams.id = 0;
    userParams.loginName = '';
    userParams.realName = '';
    userParams.roleIds = [];
    nextTick(() => {
        formRef.value.clearValidate('loginName');
        formRef.value.clearValidate('realName');
        formRef.value.clearValidate('roleIds');
    })
}
const updateUser = (row: any) => {
    nextTick(() => {
        formRef.value.clearValidate('loginName');
        formRef.value.clearValidate('realName');
        formRef.value.clearValidate('roleIds');
    })
    dialogFormVisible.value = true;
    Object.assign(userParams, row);
}
const validatorName = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack();
    } else {
        callBack(new Error('登录名长度大于等于两位'))
    }
}
const validatorDesc = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 4) {
        callBack();
    } else {
        callBack(new Error('用户名长度大于等于四位'))
    }
}
const validatorRoleId = (rule: any, value: any, callBack: any) => {
    if (value.length >= 1) {
        callBack();
    } else {
        callBack(new Error('角色不能为空'))
    }
}
const rules = {
    loginName: [
        { required: true, trigger: 'blur', validator: validatorName }
    ],
    realName: [
        { required: true, trigger: 'blur', validator: validatorDesc }
    ],
    roleIds: [
        { required: true, trigger: 'blur', validator: validatorRoleId }
    ]
}
const removeUser = async (id: number) => {
    let result = await reqDeleteUserApi(id);
    if (result.status == 200) {
        ElMessage({
            type: 'success',
            message: '删除用户成功'
        });
        getUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    } else {
        ElMessage({
            type: 'error',
            message: '删除用户失败'
        })
    }
}
const cancel = () => {
    dialogFormVisible.value = false;
}
const confirm = async () => {
    await formRef.value.validate();
    let result: any = await reqAddOrUpdateUserApi(userParams);
    if (result.status == 200) {
        dialogFormVisible.value = false;
        ElMessage({
            type: 'success',
            message: userParams.id ? '修改用户成功' : '添加用户成功'
        });
        getUser(userParams.id ? pageNo.value : 1);
    } else {
        ElMessage({
            type: 'error',
            message: userParams.id ? '修改用户失败' : '添加用户失败'
        });
        dialogFormVisible.value = false;
    }
}
const onSearch = () => {
    loading.value = true;
    getUser();
    loading.value = false;
}
const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
}
const handleSelectionChange = (val: []) => {
    deleteIds = val
}
const deleteUser = () => {
    console.log(deleteIds)
}
</script>

<style lang='scss' scoped></style>